<template>
  <!--  我的代办-->
  <div class="app-container">
    <!-- 工具栏 -->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <el-input
          v-model="query.businessKey"
          size="small"
          clearable
          placeholder="输入申请单号"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleSearch"
        />
        <el-input
          v-model="query.taskName"
          size="small"
          clearable
          placeholder="输入任务名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleSearch"
        />
        <el-date-picker
          v-model="timeValue"
          class="filter-item"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
        <el-button size="small" type="primary" class="filter-item" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="small" class="filter-item" @click="resetSearch">
          重置
        </el-button>
      </div>
    </div>

    <!-- 办理弹窗 -->
    <el-dialog
      append-to-body
      :before-close="resetForm"
      :close-on-click-modal="false"
      :visible.sync="showDialog"
      :title="processName"
      width="1000px"
      class="approval-dialog"
    >
      <div class="block">
        <!-- 审批历史（移至顶部） -->
        <div class="history-container">
          <h3 class="history-title">审批历史记录</h3>
          <el-timeline class="timeline-custom">
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              color="#0bbd87"
              size="normal"
              placement="top"
              :timestamp="activity.startTime"
            >
              <el-card class="timeline-card">
                <p>{{ activity.assignee + '--' + activity.taskName }}</p>
                <p v-if="activity.comment">审批意见：{{ JSON.parse(activity.comment).approvalResion }}</p>
                <p v-if="activity.comment">审批结果：{{ JSON.parse(activity.comment).approvalResult }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 表单区域（一行两列布局） -->
        <div class="form-container">
          <el-row>
            <el-col :span="24" style="padding-top: 20px;">
              <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px" class="approval-form">
                <!-- 编目上线/下线申请表单 -->
                <template v-if="processName === '编目上线申请' || processName === '编目下线申请'">
                  <div class="form-section">
                    <h3 class="section-title">基础信息</h3>
                    <div class="form-grid">
                      <el-form-item label="申请编号" class="form-item">
                        <el-input v-model="form.applicationCode" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请状态" class="form-item">
                        <el-input v-model="form.applicationStatus" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请类型" class="form-item">
                        <el-input v-model="form.applicationType" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人" class="form-item">
                        <el-input v-model="form.applicationUser" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="编目名称" class="form-item full-width">
                        <el-input v-model="form.catalogName" disabled class="form-input" />
                      </el-form-item>
                    </div>
                  </div>
                </template>

                <!-- 编目使用申请表单 -->
                <template v-else-if="processName === '编目使用申请'">
                  <div class="form-section">
                    <h3 class="section-title">申请人信息</h3>
                    <div class="form-grid">
                      <el-form-item label="编目名称" class="form-item">
                        <el-input v-model="form.catalogName" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请编号" class="form-item">
                        <el-input v-model="form.appNub" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请单位" class="form-item">
                        <el-input v-model="form.appDept" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人姓名" class="form-item">
                        <el-input v-model="form.appName" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人电话" class="form-item">
                        <el-input v-model="form.appPhone" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人邮箱" class="form-item">
                        <el-input v-model="form.appEmail" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="是否超期未处理" class="form-item">
                        <el-input v-model="form.isOverdue" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item class="form-item" />
                    </div>
                  </div>

                  <div class="form-section">
                    <h3 class="section-title">申请详情</h3>
                    <div class="form-grid">
                      <el-form-item label="应用场景" class="form-item">
                        <el-input v-model="form.appScenarios" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="应用事项" class="form-item">
                        <el-input v-model="form.appMatters" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请依据" class="form-item">
                        <el-input v-model="form.appBasis" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请状态" class="form-item">
                        <el-input v-model="form.appStu" disabled class="form-input" />
                      </el-form-item>
                    </div>
                  </div>

                  <div class="form-section">
                    <h3 class="section-title">系统与调用信息</h3>
                    <div class="form-grid">
                      <el-form-item label="业务系统" class="form-item">
                        <el-input v-model="form.appSystem" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="业务系统IP" class="form-item">
                        <el-input v-model="form.appId" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="系统部署地址" class="form-item">
                        <el-input v-model="form.appSystemLocation" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="调用方式" class="form-item">
                        <el-input v-model="form.appMethod" disabled class="form-input" />
                      </el-form-item>

                      <!-- 动态显示：API类型（appMethod=0） -->
                      <template v-if="form.appMethod === 'API'">
                        <el-form-item label="使用期限(天)" class="form-item">
                          <el-input v-model="form.apiLife" disabled class="form-input" />
                        </el-form-item>
                        <el-form-item label="API调用频率(天)" class="form-item">
                          <el-input v-model="form.apiCallFrequency" disabled class="form-input" />
                        </el-form-item>
                        <el-form-item label="API调用起始时间" class="form-item">
                          <el-input v-model="form.apiTimeStart" disabled class="form-input" />
                        </el-form-item>
                        <el-form-item label="API调用结束时间" class="form-item">
                          <el-input v-model="form.apiTimeEnd" disabled class="form-input" />
                        </el-form-item>
                      </template>
                      <!-- 动态显示：数据库类型（appMethod=1） -->
                      <template v-if="form.appMethod === '数据库'">
                        <el-form-item label="数据库地址(ip+端口)" class="form-item">
                          <el-input v-model="form.databaseAddress" disabled class="form-input" />
                        </el-form-item>
                      </template>
                      <!-- 始终显示：附件和备注 -->
                      <el-form-item label="附件" class="form-item">
                        <!-- <el-input v-model="form.attachment" disabled class="form-input" /> -->
                        <span v-if="form.dataFiles && form.dataFiles.length > 0">
                          <span v-for="item in form.dataFiles" :key="item.id" class="file-item" @click="downLoad(item)">
                            {{ item.name }}
                          </span>
                        </span>
                        <span v-else class="empty-tip">无附件</span>
                      </el-form-item>
                      <el-form-item label="备注" class="form-item full-width">
                        <el-input v-model="form.remarks" disabled class="form-input" type="textarea" :rows="2" />
                      </el-form-item>
                    </div>
                  </div>
                </template>

                <!-- 数据需求申请 -->
                <template v-else-if="processName === '数据需求申请'">
                  <div class="form-section">
                    <div class="form-grid">
                      <el-form-item label="需求资源名称" class="form-item">
                        <el-input v-model="form.dataName" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="服务方式" class="form-item">
                        <el-input v-model="form.type" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="数据项" class="form-item">
                        <el-input v-model="form.dataItem" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="资源覆盖范围" class="form-item">
                        <el-input v-model="form.resourceRange" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人姓名" class="form-item">
                        <el-input v-model="form.sqr" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人手机号" class="form-item">
                        <el-input v-model="form.phone" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="申请人邮箱" class="form-item">
                        <el-input v-model="form.email" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="应用场景" class="form-item">
                        <el-input v-model="form.appScene" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="起始时间" class="form-item">
                        <el-input v-model="form.startTime" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="结束时间" class="form-item">
                        <el-input v-model="form.endTime" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="审批状态" class="form-item">
                        <el-input v-model="form.spzt" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="数据局审批人" class="form-item">
                        <el-input v-model="form.spr" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="数据所属部门审批人" class="form-item">
                        <el-input v-model="form.dataDeptSpr" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="数据局审批意见" class="form-item">
                        <el-input v-model="form.spyj" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="数据所属部门审批意见" class="form-item">
                        <el-input v-model="form.dataDeptSpyj" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="数据所属部门" class="form-item">
                        <el-input v-model="form.dataDept" disabled class="form-input" />
                      </el-form-item>
                      <el-form-item label="文件" class="form-item">

                        <span v-if="form.dataFile && form.dataFile.length > 0">
                          <span v-for="item in form.dataFile" :key="item.id" class="file-item" @click="downLoad(item)">
                            {{ item.name }}
                          </span>
                        </span>
                        <span v-else> <el-tag type="danger">暂无附件</el-tag>

                        </span>
                      </el-form-item>
                    </div>
                  </div>
                </template>

                <!-- 需求督办申请 -->
                <template v-else-if="processName === '需求督办申请'">
                  <div class="form-section">
                    <div class="form-grid">
                      <el-form-item label="需求资源名称：" class="form-item">
                        <div class="form-content">{{ form.demandName || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="督办人：" class="form-item">
                        <div class="form-content">{{ form.dbr || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="督办内容：" class="form-item">
                        <div class="form-content">{{ form.dbnr || '未选择' }}</div>
                      </el-form-item>

                      <el-form-item label="状态：" class="form-item">
                        <div class="form-content">{{ form.status || '未填写' }}</div>
                      </el-form-item>
                      <el-form-item label="被督办人：" class="form-item">
                        <div class="form-content">{{ form.bdbr || '未选择' }}</div>
                      </el-form-item>

                      <el-form-item label="回复内容：" class="form-item">
                        <div class="form-content">{{ form.hfnr || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="督办编号：" class="form-item">
                        <div class="form-content">{{ form.dbbh || '未选择' }}</div>
                      </el-form-item>
                    </div>
                  </div>
                </template>

                <!-- 责任撤销申请 -->
                <template v-else-if="processName === '责任撤销申请'">
                  <div class="form-section">
                    <div class="form-grid">
                      <el-form-item label="数据责任名称：" class="form-item">
                        <div class="form-content">{{ form.taskName || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="数据责任类型：" class="form-item">
                        <div class="form-content">{{ form.taskType || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="数据责任人：" class="form-item">
                        <div class="form-content">{{ form.taskUser || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="撤销理由：" class="form-item">
                        <div class="form-content">{{ form.deleteReason || '未选择' }}</div>
                      </el-form-item>

                      <el-form-item label="数据责任描述：" class="form-item">
                        <div class="form-content">{{ form.taskDescri || '未选择' }}</div>
                      </el-form-item>

                      <el-form-item label="数据责任状态：" class="form-item">
                        <div class="form-content">{{ form.taskStatus || '未填写' }}</div>
                      </el-form-item>
                      <el-form-item label="审批意见：" class="form-item">
                        <div class="form-content">{{ form.spyj || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="审批状态：" class="form-item">
                        <!-- 给数据分级加标签样式，突出重要性 -->
                        <div class="form-content">{{ form.spzt || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="审批人：" class="form-item">
                        <div class="form-content">{{ form.spr || '未选择' }}</div>
                      </el-form-item>

                      <el-form-item label="审批编号：" class="form-item">
                        <div class="form-content">{{ form.spbh || '未填写' }}</div>
                      </el-form-item>

                      <el-form-item label="审批时间：" class="form-item">
                        <div class="form-content">{{ form.spsj || '未填写' }}</div>
                      </el-form-item>
                      <el-form-item label="文件" class="form-item">

                        <span v-if="form.file && form.file.name" class="file-item" @click="downLoad(form.file)">
                          {{ form.file && form.file.name }}
                        </span>
                        <span v-else> <el-tag type="danger">暂无附件</el-tag>

                        </span>
                      </el-form-item>
                    </div>
                  </div>
                </template>

                <!-- 审批区域（所有流程共用） -->
                <div class="form-section approval-section">
                  <h3 class="section-title">审批操作</h3>
                  <div class="form-grid">
                    <el-form-item
                      v-if="processNameFlag !== '需求督办申请'"
                      label="审批结果"
                      prop="result"
                      class="form-item"
                    >
                      <el-radio-group v-model="form.result" class="radio-group">
                        <el-radio :label="0" class="radio-item">同意</el-radio>
                        <el-radio :label="1" class="radio-item">拒绝</el-radio>
                        <el-radio
                          v-if="processNameFlag === '数据需求申请' && taskNameFlag === '数据主管部门初审'"
                          :label="2"
                          class="radio-item"
                        >通过且已有数据
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item
                      v-if="processNameFlag === '数据需求申请' && ((taskNameFlag === '数据主管部门初审' && form.result !== 0) || taskNameFlag === '数据主管部门复审') && (form.result === 0 || form.result === 2)"
                      label="编目名称"
                      prop="sjbmName"
                      class="form-item full-width"
                    >
                      <el-input v-model="form.sjbmName" :rows="4" class="form-input" placeholder="请输入编目名称" />
                    </el-form-item>
                    <el-form-item
                      v-if="form.result === 0 && processNameFlag === '数据需求申请' && taskNameFlag === '数据主管部门初审'"
                      label="数据源部门"
                      prop="sjybm"
                      class="form-item full-width"
                    >
                      <el-select v-model="form.deptName" placeholder="请选择申请部门" @change="onDeptSelect">
                        <el-option v-for="item in optionsBm" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="form.result === 0 && processNameFlag === '数据需求申请' && taskNameFlag === '数据主管部门初审'"
                      :error="customError"
                      :required="true"
                      label="审批人"
                      class="form-item"
                    >
                      <el-select
                        v-model="approverId"
                        placeholder="请选择审批人"
                        :disabled="approverOptions.length == 0"
                        style="width: 100%"
                        clearable
                      >
                        <el-option
                          v-for="(item) in approverOptions"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="审批意见" prop="comment" class="form-item full-width">
                      <el-input
                        v-model="form.comment"
                        type="textarea"
                        :rows="4"
                        class="form-input"
                        placeholder="请输入审批意见..."
                      />
                    </el-form-item>
                  </div>
                </div>
              </el-form>
            </el-col>
          </el-row>
        </div>

        <div style="text-align: right;" class="dialog-footer">
          <el-button type="text" @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitApproval()">确认</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 表格区域 -->
    <div slot="header" class="clearfix">
      <span class="role-span">我的待办任务列表</span>
    </div>
    <el-table highlight-current-row style="width: 100%;margin-top: 10px" :data="taskList" border>
      <el-table-column prop="businessKey" label="申请单号" width="280px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="点击查看详情" placement="top">
            <!-- 添加可点击样式 -->
            <span
              style="color: #409EFF; cursor: pointer; text-decoration: underline;"
              @click="handleViewDetails(scope.row)"
            >
              {{ scope.row.businessKey }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="taskName" label="任务名称" />
      <el-table-column prop="processName" label="流程名称" />
      <el-table-column prop="starter" label="申请人" />
      <el-table-column prop="startTime" label="申请时间" />
      <el-table-column label="操作" width="130px" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" icon="el-icon-folder-opened" @click="openHandleDialog(scope.row)">办理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total-num="totalCount"
      :current-page="currentPage"
      @handleCurrentChange="changePage"
      @handlePageSizeChange="handlePageSizeChange"
    />
    <ZybmInfoDialog ref="detailsDialog" />
    <!-- 数据需求申请对话框 -->
    <sjxqsqDialog ref="sjxqsqDialogRef" />
    <!-- 需求督办申请对话框-->
    <xqdbsqDialog ref="xqdbsqDialogRef" />
    <!--  责任撤销对话框  -->
    <sjzrDialog ref="sjzrDialogRef" />
  </div>
</template>

<script>
import Pagination from '@/components/common/Pagination.vue'
import { downloadFile } from '@/api/xwZx'

import {
  getCatalogDetail,
  getHistory,
  getsSharingAppDetail,
  getInteractDetail,
  getSupervisionDetail,
  getDetailBySpbh
} from '@/api/taskManagement/allTasksInfo'
import {
  getMyToDoTasks,
  getApplicationDetail,
  getCompleteApp,
  getCompleteSharingApp,
  getAuditdemand,
  getExaminedb,
  getDatataskComplete
} from '@/api/taskManagement/myApplicationInfo'
import ZybmInfoDialog from '@/views/TaskManagement/ApprovalRecords/ZybmInfoDialog.vue'
import sjxqsqDialog from '@/views/TaskManagement/ApprovalRecords/sjxqsqDialog.vue'
import xqdbsqDialog from '@/views/TaskManagement/ApprovalRecords/xqdbsqDialog.vue'
import { getAlldept, getDatadeptspr } from '@/api/supplyDemand/dataRequirements'
import sjzrDialog from '@/views/TaskManagement/ApprovalRecords/sjzrDialog.vue'

export default {
  name: 'SimpleMyTask',
  components: {
    sjzrDialog,
    sjxqsqDialog,
    ZybmInfoDialog,
    xqdbsqDialog,
    Pagination
  },
  data() {
    return {
      timeValue: [],
      taskNameFlag: '',
      approverOptions: [],
      optionsBm: [],
      processNameFlag: '',
      methodMap: { 0: 'API', 1: '数据库', 2: '文件' },
      statusFl: { 0: '未确定', 1: '已确定' },
      taskName: '',
      typeMap: { 0: '上线', 1: '下线' },
      statusMap: { 0: '待处理', 1: '审批通过', 2: '审批拒绝', 3: '已撤销' },
      spztZrcxMAP: { 0: '待审核', 1: '审核通过', 2: '审核退回' },
      spztMap: {
        0: '待数据局初审',
        1: '数据局初审通过，数据源部门审核中',
        2: '数据局初审通过且已形成数据编目',
        3: '数据局初审退回',
        4: '数据源部门审核通过，数据局二审',
        5: '数据源部门退回',
        6: '数据局二审退回至数据源部门',
        7: '数据局二审通过'
      },
      // 表格数据
      taskList: [],
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,
      // 查询条件
      query: {
        businessKey: '',
        taskName: ''
      },

      // 弹窗相关
      showDialog: false,
      processName: '',
      approverId: '',
      form: {
        businessKey: '',
        sjbmName: '',
        approverId: '',
        deptName: '',
        comment: '',
        result: 0,
        id: '',
        appNub: '',
        appDept: '',
        appPhone: '',
        appEmail: '',
        appName: '',
        appScenarios: '',
        appMatters: '',
        appBasis: '',
        appSystem: '',
        appId: '',
        appSystemLocation: '',
        appMethod: '',
        apiCallFrequency: '',
        apiTimeStart: '',
        apiTimeEnd: '',
        databaseAddress: '',
        catalogName: '',
        appStu: '',
        remarks: '',
        apiLife: '',
        dataFiles: [],
        dataFile: []
      },
      activities: [],

      // 验证规则
      rules: {
        comment: [{ required: true, message: '请填写审批意见', trigger: 'blur' }],
        result: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
        sjbmName: [{ required: true, message: '请填写数据编目名称', trigger: 'blur' }],
        approverId: [ // 新增审批人ID验证
          { required: true, message: '请选择审批人', trigger: 'change' }
        ]
      },
      customError: ''
    }
  },
  watch: {
    approverId(n, o) {
      console.log(1112, n, o)
      this.form.approverId = n
    }
  },
  created() {
    this.loadTaskList()
  },
  methods: {
    validateApproverId() {
      if (this.processNameFlag === '数据需求申请' &&
        this.form.result === 0 &&
        this.taskNameFlag === '数据主管部门初审'
      ) {
        const value = this.approverId
        // 必填校验：为空则提示错误
        if (!value) {
          this.customError = '请选择审批人'
          return false // 校验失败
        } else {
          this.customError = '' // 清空错误提示
          return true // 校验通过
        }
      } else {
        return true
      }
    },
    onDeptSelect(deptId) {
      this.approverOptions = [] // 清空审批人选项列表
      this.approverId = '' // 清空已选审批人ID
      if (!deptId) {
        return
      }
      // 调用审批人接口（参数为选中的部门ID）
      getDatadeptspr(deptId).then(res => {
        const approverData = res.data || res
        this.approverOptions = approverData.map(user => ({
          name: user.nickName || '未知用户', // 显示用户昵称（兜底避免空值）
          value: String(user.id) // 绑定用户唯一ID（与form.approverId匹配）
        }))
        console.log('最终审批人选项：', this.approverOptions)
        // 优化体验：若只有1个审批人，自动选中
        if (this.approverOptions.length === 1) {
          this.approverId = this.approverOptions[0].value
          this.$message.success(`已自动选中审批人：${this.approverOptions[0].name}`)
        }
      })
        .catch(error => {
          // 错误处理：清空数据+提示用户
          this.approverOptions = []
          this.approverId = ''
          console.error('加载审批人失败:', error)
          // this.$message.error('审批人加载失败，请重新选择部门')
        })
    },
    getAlldeptFn() {
      getAlldept().then(res => {
        console.log(res, '部门')
        this.optionsBm = res
      })
    },
    // 处理查看编目详情点击事件
    handleViewDetails(row) {
      console.log(row.processName, 'row')
      if (row.processName === '编目上线申请' || row.processName === '编目下线申请' || row.processName === '编目使用申请') {
        getCatalogDetail(row.businessKey).then(res => {
          console.log(res, '详情')
          this.$refs.detailsDialog.setDetailData(res)
        })
      } else if (row.processName === '数据需求申请') {
        getInteractDetail(row.businessKey).then(res => {
          console.log(res, '数据需求申请')
          this.$refs.sjxqsqDialogRef.setDetailData(res)
        })
      } else if (row.processName === '需求督办申请') {
        getSupervisionDetail(row.businessKey).then(res => {
          console.log(res, '需求督办申请')
          this.$refs.xqdbsqDialogRef.setDetailData(res)
        })
      } else if (row.processName === '责任撤销申请') {
        getDetailBySpbh(row.businessKey).then(res => {
          console.log(res, '责任撤销申请')
          this.$refs.sjzrDialogRef.setDetailData(res)
        })
      }
    },
    // 加载任务列表
    loadTaskList() {
      getMyToDoTasks({
        page: this.currentPage,
        size: this.pageSize,
        businessKey: this.query.businessKey || null,
        taskName: this.query.taskName,
        startTime: this.timeValue ? this.timeValue[0] : null,
        endTime: this.timeValue ? this.timeValue[1] : null
      }).then(response => {
        this.taskList = response.content
        this.totalCount = response.totalElements
      }).catch(error => {
        console.error('获取任务列表失败:', error)
      })
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadTaskList()
    },

    // 重置搜索
    resetSearch() {
      this.query = {
        businessKey: '',
        taskName: ''
      }
      this.timeValue = null
      this.handleSearch()
    },

    // 切换分页
    changePage(page) {
      this.currentPage = page
      this.loadTaskList()
    },

    handlePageSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.loadTaskList()
    },

    // 打开办理弹窗
    // 打开办理弹窗
    openHandleDialog(row) {
      console.log(row, 'row')
      this.getAlldeptFn()
      console.log(row.processName, '点击办理')
      this.processNameFlag = row.processName
      this.processName = row.processName
      this.taskNameFlag = row.taskName
      this.form.id = row.businessKey
      // 根据流程名称判断调用不同接口
      if (row.processName === '编目上线申请' || row.processName === '编目下线申请') {
        // 编目上线/下线申请调用原接口
        getApplicationDetail(row.businessKey).then(res => {
          const typeText = this.typeMap[res.applicationType] || '未知类型'
          const statusText = this.statusMap[res.applicationStatus] || '未知状态'
          // this.processName = res
          this.form = {
            applicationCode: res.applicationCode,
            applicationStatus: statusText,
            applicationType: typeText,
            applicationUser: res.applicationUser,
            catalogName: res.catalogName,
            id: res.id
          }
          this.showDialog = true
        })
      } else if (row.processName === '编目使用申请') {
        // 编目使用申请调用其他接口（假设接口名为getUseApplicationDetail）
        getsSharingAppDetail(row.businessKey).then(res => {
          this.form = {
            ...this.form, // 保留原有默认值（如result:1）
            isOverdue: res.isOverdue === 0 ? '是' : '否',
            appNub: res.appNub,
            appDept: res.appDept,
            appPhone: res.appPhone,
            appEmail: res.appEmail,
            appName: res.appName,
            appScenarios: res.appScenarios,
            appMatters: res.appMatters,
            appBasis: res.appBasis,
            appSystem: res.appSystem,
            appId: res.appId,
            appSystemLocation: res.appSystemLocation,
            // 转换调用方式为中文
            appMethod: this.methodMap[res.appMethod] || res.appMethod,
            apiCallFrequency: res.apiCallFrequency,
            apiTimeStart: res.apiTimeStart,
            apiTimeEnd: res.apiTimeEnd,
            databaseAddress: res.databaseAddress,
            catalogName: res.catalogName,
            // 转换申请状态为中文（复用原有statusMap）
            appStu: this.statusMap[res.appStu] || res.appStu,
            remarks: res.remarks,
            apiLife: res.apiLife,
            id: res.id, // 用于提交审批的ID
            dataFiles: res.dataFiles
          }
          this.showDialog = true
        }).catch(error => {
          console.error('获取编目使用申请详情失败:', error)
        })
      } else if (row.processName === '数据需求申请') {
        getInteractDetail(row.businessKey).then(res => {
          console.log(res, '数据需求申请123')
          this.form = {
            ...res,
            type: this.methodMap[res.type] || res.type,
            spzt: this.spztMap[res.spzt] || res.spzt,
            businessKey: row.businessKey

          }
        })
      } else if (row.processName === '需求督办申请') {
        getSupervisionDetail(row.businessKey).then(res => {
          console.log(res, '数据需求申请123')
          this.form = {
            ...res,
            status: this.statusFl[res.status] || res.status
          }
        })
      } else if (row.processName === '责任撤销申请') {
        getDetailBySpbh(row.businessKey).then(res => {
          console.log(res, '责任撤销申请')
          this.form = {
            ...res,
            spzt: this.spztZrcxMAP[res.spzt] || res.spzt
          }
        })
      }

      // 获取审批历史的逻辑保持不变
      getHistory(
        row.processInstanceId,
        { page: 0, size: 999 }
      ).then(response => {
        this.activities = response.content
      }).catch(error => {
        console.error('获取审批记录失败:', error)
      })

      this.showDialog = true
    },

    // 重置表单
    resetForm(done) {
      this.resetFormData() // 调用通用重置方法
      // 检查done是否为函数，如果是则调用（用于对话框关闭时）
      if (typeof done === 'function') {
        done()
      }
    },

    // 新增：通用表单重置方法
    resetFormData() {
      this.form = {
        // 基础字段重置
        businessKey: '',
        starter: '',
        startTime: '',
        comment: '',
        result: 0, // 默认选中"同意"
        id: '',
        sjbmName: '',
        approverId: '',
        deptName: '',

        // 编目使用申请特有字段重置
        appNub: '',
        appDept: '',
        appPhone: '',
        appEmail: '',
        appName: '',
        appScenarios: '',
        appMatters: '',
        appBasis: '',
        appSystem: '',
        appId: '',
        appSystemLocation: '',
        appMethod: '',
        apiCallFrequency: '',
        apiTimeStart: '',
        apiTimeEnd: '',
        databaseAddress: '',
        catalogName: '',
        appStu: '',
        remarks: '',
        apiLife: ''
      }
      this.approverOptions = [] // 清空审批人选项列表
      // 清除表单验证状态
      if (this.$refs.form) {
        try {
          this.$refs.form.resetFields()
        } catch (e) {
          console.log(e)
        }
      }
    },

    // 提交审批
    submitApproval() {
      if (!this.validateApproverId()) {
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.processNameFlag)
          // 根据流程名称调用不同接口
          if (this.processNameFlag === '编目上线申请' || this.processNameFlag === '编目下线申请') {
            const commonData = {
              id: this.form.id,
              approvalResult: this.form.result,
              approvalResion: this.form.comment
            }
            // 编目上线/下线申请：调用原有接口
            getCompleteApp(commonData)
              .then(res => {
                this.$message({
                  message: res,
                  type: 'success'
                })
                this.showDialog = false
                this.resetForm()
                this.loadTaskList()
              })
          } else if (this.processNameFlag === '编目使用申请') {
            // 编目使用申请：调用新接口（假设接口名为completeUseApplication）
            const dataApi = {
              id: this.form.id,
              approvalResult: this.form.result,
              approvalResion: this.form.comment,
              approvalType: 1
            }
            getCompleteSharingApp(dataApi)
              .then(res => {
                this.$message({
                  message: res,
                  type: 'success'
                })
                this.showDialog = false
                this.resetForm()
                this.loadTaskList()
              })
          } else if (this.processNameFlag === '数据需求申请') {
            console.log('数据需求申请')
            const dataApi = {
              spbh: this.form.businessKey,
              spzt: this.form.result,
              auditReply: this.form.comment,
              sjbmName: this.form.sjbmName,
              dataDept: this.form.deptName,
              dataDeptSpr: this.form.approverId
            }
            getAuditdemand(dataApi).then(res => {
              this.$message({
                message: res,
                type: 'success'
              })
              this.showDialog = false
              this.resetForm()
              this.loadTaskList()
            })
          } else if (this.processNameFlag === '需求督办申请') {
            const dataApi = {
              spzt: 1,
              spyj: this.form.comment,
              dbbh: this.form.businessKey
            }
            getExaminedb(dataApi).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.showDialog = false
              this.resetForm()
              this.loadTaskList()
            })
          } else if (this.processNameFlag === '责任撤销申请') {
            const dataApi = {
              id: this.form.id,
              spzt: this.form.result,
              spyj: this.form.comment
            }
            getDatataskComplete(dataApi).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.showDialog = false
              this.resetForm()
              this.loadTaskList()
            })
          }
        }
      })
    },
    downLoad(item) {
      console.log(item)
      downloadFile(item.id).then(res => {
        // 3. 将 blob 转换为可下载的链接
        const blob = new Blob([res], {
          // 根据文件类型设置 MIME 类型
          // 常见类型：application/pdf、image/jpeg、application/vnd.ms-excel 等
          type: 'application/octet-stream'
        })

        // 4. 创建 a 标签并触发下载
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = item.name
        document.body.appendChild(a)
        a.click() // 触发点击下载

        // 5. 清理资源
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url) // 释放 blob URL

        this.$message.success('文件下载成功')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 弹窗整体样式
.approval-dialog {
  ::v-deep .el-dialog__body {
    padding: 15px 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

// 审批历史容器（顶部区域）
.history-container {
  padding: 10px 15px;
  background-color: #f8fafc;
  border-radius: 6px;
  margin-bottom: 15px;
  border: 1px solid #e2e8f0;
}

.history-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #334155;
  font-weight: 500;
  display: flex;
  align-items: center;

  &:before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 14px;
    background-color: #3b82f6;
    margin-right: 8px;
    border-radius: 2px;
  }
}

// 时间线样式优化
.timeline-custom {
  padding-left: 10px;

  ::v-deep .el-timeline-item {
    margin-bottom: 15px;

    &:last-child {
      margin-bottom: 0;
    }

    .el-timeline-item__tail {
      top: 16px;
      height: calc(100% - 16px);
      left: 6px;
    }

    .el-timeline-item__node {
      width: 14px;
      height: 14px;
      left: 0;
    }

    .el-timeline-item__timestamp {
      top: 0;
      font-size: 12px;
      color: #64748b;
      margin-bottom: 5px;
    }
  }
}

.timeline-card {
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: all 0.2s;

  &:hover {
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
  }

  ::v-deep .el-card__body {
    padding: 10px 15px;
  }

  p {
    margin: 5px 0;
    font-size: 13px;

    &:first-child {
      color: #1e293b;
      font-weight: 500;
    }

    &:not(:first-child) {
      color: #64748b;
      padding-left: 5px;
    }
  }
}

// 表单容器样式
.form-container {
  padding: 5px;
}

// 表单分区样式
.form-section {
  margin-bottom: 18px;
  padding: 12px 15px;
  background-color: #ffffff;
  border-radius: 6px;
  border: 1px solid #f1f5f9;
}

.section-title {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #1e40af;
  font-weight: 500;
  padding-bottom: 8px;
  border-bottom: 1px dashed #dbeafe;
}

// 一行两列网格布局
.form-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px; // 列之间的间距
}

// 表单项样式（一行两列）
.form-item {
  flex: 1; // 自动分配宽度，实现一行两列
  min-width: 33%; // 最小宽度，避免过窄
  margin-bottom: 8px !important;

  &.full-width {
    flex: 0 0 100%; // 占满整行
  }

  .el-form-item__label {
    color: #475569;
    font-size: 12px;
    padding-right: 10px;
    line-height: 1.5;
  }

  .el-form-item__content {
    line-height: 1.5;
  }
}

// 输入框样式
.form-input {
  width: 100% !important;
  border-radius: 4px;
  font-size: 12px;
  height: 32px;

  &:disabled {
    background-color: #f8fafc;
    color: #64748b;
    border-color: #e2e8f0;
  }

  &:not(:disabled):focus {
    border-color: #60a5fa;
    box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2);
  }

  &.el-textarea {
    height: auto !important;
    min-height: 80px;
  }
}

// 审批区域特殊样式
.approval-section {
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
}

// 单选框组样式
.radio-group {
  display: flex;
  gap: 20px;
  padding-top: 4px;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #334155;
  font-size: 12px;

  ::v-deep .el-radio__input.is-checked .el-radio__inner {
    border-color: #3b82f6;
    background-color: #3b82f6;
  }

  ::v-deep .el-radio__input.is-checked + .el-radio__label {
    color: #3b82f6;
  }
}

// 滚动条美化
::v-deep .el-dialog__body {
  scrollbar-width: thin;
  scrollbar-color: #cbd5e1 #f1f5f9;

  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #cbd5e1;
    border-radius: 3px;
  }
}

// 底部按钮样式
.dialog-footer {
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #f1f5f9;

  ::v-deep .el-button {
    padding: 6px 16px;
    font-size: 12px;
  }

  ::v-deep .el-button--primary {
    background-color: #3b82f6;
    border-color: #3b82f6;

    &:hover {
      background-color: #2563eb;
      border-color: #2563eb;
    }
  }
}

.app-container {
  padding: 20px;
}

.filter-item {
  margin-right: 10px;
}

.date-item {
  margin-right: 10px;
  width: 240px;
}

.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.dialog-footer {
  margin-top: 20px;
}

::v-deep .el-card__body {
  padding: 0 10px;
}

::v-deep .el-timeline-item__timestamp {
  font-size: 12px;
}

.file-item {
  display: inline-block;
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
  margin-right: 8px;
  margin-bottom: 6px;
  border: 5px;
  cursor: pointer;
}
</style>
